<template>
  <div>
    <!-- Instructions Page -->
    <motion
      v-if="stage === 'instructions'"
      :initial="{ opacity: 0, y: 20 }"
      :animate="{ opacity: 1, y: 0 }"
      class="max-w-2xl mx-auto"
    >
      <div
        class="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg rounded-lg overflow-hidden"
      >
        <div class="text-center pb-8 px-6 pt-6">
          <div
            class="w-16 h-16 bg-gradient-to-br from-indigo-600 to-blue-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
          >
            <Brain class="w-8 h-8 text-white" />
          </div>
          <h2 class="text-2xl text-slate-800 font-bold">
            {{ t("workingMemoryTest.title") }}
          </h2>
          <p class="text-slate-600 mt-2">
            {{ t("workingMemoryTest.description") }}
          </p>
        </div>

        <div class="space-y-6 px-6 pb-6">
          <div
            class="bg-gradient-to-r from-indigo-50 to-blue-50 rounded-xl p-6 border border-indigo-100"
          >
            <h3
              class="font-semibold text-indigo-900 mb-4 flex items-center gap-2"
            >
              <Star class="w-5 h-5" />
              {{ t("workingMemoryTest.instructionsTitle") }}
            </h3>
            <div class="space-y-3 text-slate-700">
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                  >1</span
                >
                <p>{{ t("workingMemoryTest.instruction1") }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                  >2</span
                >
                <p>{{ t("workingMemoryTest.instruction2") }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                  >3</span
                >
                <p>{{ t("workingMemoryTest.instruction3") }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                  >4</span
                >
                <p>{{ t("workingMemoryTest.instruction4") }}</p>
              </div>
            </div>
          </div>

          <div class="grid md:grid-cols-3 gap-4">
            <div
              class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200"
            >
              <h4
                class="font-semibold text-blue-800 mb-2 flex items-center gap-2"
              >
                <Target class="w-4 h-4" />
                {{ t("workingMemoryTest.taskType_digit_span") }}
              </h4>
              <p class="text-sm text-blue-700">
                {{ t("workingMemoryTest.taskType_digit_span_desc") }}
              </p>
            </div>
            <div
              class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 border border-purple-200"
            >
              <h4
                class="font-semibold text-purple-800 mb-2 flex items-center gap-2"
              >
                <ArrowRight class="w-4 h-4" />
                {{ t("workingMemoryTest.taskType_spatial_sequence") }}
              </h4>
              <p class="text-sm text-purple-700">
                {{ t("workingMemoryTest.taskType_spatial_sequence_desc") }}
              </p>
            </div>
            <div
              class="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200"
            >
              <h4
                class="font-semibold text-green-800 mb-2 flex items-center gap-2"
              >
                <Star class="w-4 h-4" />
                {{ t("workingMemoryTest.taskType_visual_matrix") }}
              </h4>
              <p class="text-sm text-green-700">
                {{ t("workingMemoryTest.taskType_visual_matrix_desc") }}
              </p>
            </div>
          </div>

          <div class="grid md:grid-cols-3 gap-4">
            <div
              class="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200"
            >
              <div class="text-2xl font-bold text-indigo-600 mb-1">3</div>
              <div class="text-sm text-indigo-700">
                {{ t("workingMemoryTest.taskTypes") }}
              </div>
            </div>
            <div
              class="text-center p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl border border-blue-200"
            >
              <div class="text-2xl font-bold text-blue-600 mb-1">12</div>
              <div class="text-sm text-blue-700">
                {{ t("workingMemoryTest.testRounds") }}
              </div>
            </div>
            <div
              class="text-center p-4 bg-gradient-to-br from-indigo-50 to-blue-50 rounded-xl border border-indigo-200"
            >
              <div class="text-2xl font-bold text-slate-600 mb-1">
                {{ t("workingMemoryTest.adaptive") }}
              </div>
              <div class="text-sm text-slate-700">
                {{ t("workingMemoryTest.difficultyAdjustment") }}
              </div>
            </div>
          </div>

          <button
            @click="handleStartTest"
            class="w-full bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12 rounded-md font-semibold"
          >
            {{ t("workingMemoryTest.startTest") }}
          </button>
        </div>
      </div>
    </motion>

    <!-- Test Page -->
    <motion
      v-else-if="stage === 'test' && tasks.length > 0"
      :initial="{ opacity: 0, scale: 0.95 }"
      :animate="{ opacity: 1, scale: 1 }"
      class="max-w-4xl mx-auto space-y-6"
    >
      <!-- Progress Bar and Status -->
      <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
        <div class="flex items-center gap-4">
          <span
            class="bg-indigo-100 text-indigo-700 border-indigo-300 border rounded-md px-2 py-1 text-sm"
          >
            {{ t("workingMemoryTest.taskProgress") }} {{ currentTask + 1 }} /
            {{ tasks.length }}
          </span>
          <span
            class="bg-blue-100 text-blue-700 border-blue-300 border rounded-md px-2 py-1 text-sm"
          >
            {{ t("workingMemoryTest.spanLength") }}:
            {{ tasks[currentTask].spanLength }}
          </span>
          <div class="flex items-center gap-2 text-slate-600">
            <Trophy class="w-4 h-4" />
            <span class="font-semibold">{{ score }}</span>
          </div>
        </div>
      </div>

      <div class="w-full bg-gray-200 rounded-full h-2">
        <div
          class="bg-indigo-600 h-2 rounded-full transition-all duration-300"
          :style="{ width: `${(currentTask / tasks.length) * 100}%` }"
        ></div>
      </div>

      <!-- Task Instructions and Start Button -->
      <div
        class="bg-gradient-to-r from-slate-50 to-gray-50 border-slate-200 border rounded-lg overflow-hidden"
      >
        <div class="p-6">
          <h2 class="text-lg text-slate-800 text-center mb-4 font-bold">
            {{ tasks[currentTask].instruction }}
          </h2>
          <div class="space-y-4 text-center">
            <p class="text-slate-600">
              {{ t("workingMemoryTest.readInstructions") }}
            </p>
            <div
              class="bg-blue-50 border border-blue-200 rounded-lg p-4 space-y-2"
            >
              <h4 class="font-semibold text-blue-800">
                {{ t("workingMemoryTest.testFlow") }}
              </h4>
              <div class="text-sm text-blue-700 space-y-1">
                <p>{{ t("workingMemoryTest.flow1") }}</p>
                <p>{{ t("workingMemoryTest.flow2") }}</p>
                <p>{{ t("workingMemoryTest.flow3") }}</p>
              </div>
            </div>
            <button
              @click="startPresenting"
              class="bg-gradient-to-r from-indigo-600 to-blue-500 hover:from-indigo-700 hover:to-blue-600 text-white px-8 py-2 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200 rounded-md mx-auto flex items-center justify-center"
            >
              <Brain class="w-5 h-5 mr-2" />
              {{ t("workingMemoryTest.readyToStart") }}
            </button>
          </div>
        </div>
      </div>
    </motion>

    <!-- Presentation Page -->
    <motion
      v-else-if="stage === 'presenting' && tasks.length > 0"
      :initial="{ opacity: 0, scale: 0.95 }"
      :animate="{ opacity: 1, scale: 1 }"
      class="max-w-4xl mx-auto space-y-6"
    >
      <div
        class="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg rounded-lg overflow-hidden"
      >
        <div class="p-8">
          <div class="text-center">
            <template v-if="tasks[currentTask].type === 'digit_span'">
              <div class="space-y-4">
                <div class="text-sm text-slate-500 mb-2">
                  {{ t("workingMemoryTest.presenting_digit_span") }}
                </div>
                <div class="text-8xl font-mono font-bold text-indigo-600">
                  {{ presentingItem || "" }}
                </div>
                <div
                  v-if="typeof presentingItem === 'number'"
                  class="text-lg text-slate-600"
                >
                  {{ currentIndex + 1 }} / {{ currentSequence.length }}
                </div>
                <div
                  v-if="
                    typeof presentingItem === 'string' &&
                    presentingItem.includes('Ready')
                  "
                  class="text-base text-slate-500"
                >
                  {{ t("workingMemoryTest.presenting_focus") }}
                </div>
              </div>
            </template>

            <template
              v-else-if="tasks[currentTask].type === 'spatial_sequence'"
            >
              <div class="space-y-4">
                <div class="text-sm text-slate-500 mb-2">
                  {{ t("workingMemoryTest.presenting_spatial_sequence") }}
                </div>

                <!-- Display countdown or hint text -->
                <div
                  v-if="typeof presentingItem === 'string'"
                  class="text-2xl font-bold text-indigo-600 mb-4"
                >
                  {{ presentingItem }}
                </div>

                <div class="grid grid-cols-3 gap-4 max-w-xs mx-auto">
                  <div
                    v-for="i in 9"
                    :key="i"
                    :class="[
                      'w-20 h-20 rounded-lg border-2 transition-all duration-300 relative',
                      isSpatialCellHighlighted(i)
                        ? 'bg-indigo-500 border-indigo-600 shadow-lg scale-110'
                        : 'bg-slate-100 border-slate-300',
                    ]"
                  >
                    <div
                      :class="[
                        'absolute top-1 left-1 text-xs font-mono',
                        isSpatialCellHighlighted(i)
                          ? 'text-white'
                          : 'text-slate-400',
                      ]"
                    >
                      {{ getSpatialCellPosition(i).x + 1 }},{{
                        getSpatialCellPosition(i).y + 1
                      }}
                    </div>
                  </div>
                </div>

                <div
                  v-if="
                    presentingItem &&
                    typeof presentingItem === 'object' &&
                    'x' in presentingItem &&
                    typeof presentingItem.x === 'number'
                  "
                  class="text-lg text-slate-600"
                >
                  {{ currentIndex + 1 }} / {{ currentSequence.length }}
                </div>
              </div>
            </template>

            <template v-else-if="tasks[currentTask].type === 'visual_matrix'">
              <div class="space-y-4">
                <div class="text-sm text-slate-500 mb-2">
                  {{ t("workingMemoryTest.presenting_visual_matrix") }}
                </div>

                <!-- Display countdown or hint text -->
                <div
                  v-if="typeof presentingItem === 'string'"
                  class="text-2xl font-bold text-indigo-600 mb-4"
                >
                  {{ presentingItem }}
                </div>

                <div
                  class="grid gap-2 max-w-md mx-auto"
                  :style="{ gridTemplateColumns: `repeat(${matrixSize}, 1fr)` }"
                >
                  <div
                    v-for="(cell, index) in matrixCells"
                    :key="index"
                    :class="[
                      'w-16 h-16 rounded border-2 transition-all duration-300',
                      cell.highlighted
                        ? 'bg-indigo-500 border-indigo-600 shadow-lg'
                        : 'bg-slate-100 border-slate-300',
                    ]"
                  />
                </div>

                <div v-if="!presentingItem">
                  <div class="text-lg text-slate-600">
                    {{ t("workingMemoryTest.presenting_remember_all") }}
                  </div>
                  <div class="text-sm text-slate-500">
                    {{ t("workingMemoryTest.presenting_duration") }}
                  </div>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </motion>

    <!-- Recall Page -->
    <motion
      v-else-if="stage === 'recall' && tasks.length > 0"
      :initial="{ opacity: 0, scale: 0.95 }"
      :animate="{ opacity: 1, scale: 1 }"
      class="max-w-4xl mx-auto space-y-6"
    >
      <div
        class="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg rounded-lg overflow-hidden"
      >
        <div class="p-6">
          <h2 class="text-lg text-slate-800 text-center font-bold">
            {{ t("workingMemoryTest.recallTitle") }}
          </h2>
        </div>
        <div class="space-y-6 px-6 pb-6">
          <template v-if="tasks[currentTask].type === 'digit_span'">
            <div class="space-y-4">
              <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <h4 class="font-semibold text-blue-800 mb-2">
                  {{ t("workingMemoryTest.recall_input_instructions") }}
                </h4>
                <p class="text-sm text-blue-700">
                  {{
                    tasks[currentTask].reverse
                      ? t("workingMemoryTest.recall_digit_span_reverse")
                      : t("workingMemoryTest.recall_digit_span_forward")
                  }}
                </p>
                <p class="text-xs text-blue-600 mt-1">
                  {{ t("workingMemoryTest.recall_example") }}
                  {{
                    tasks[currentTask].reverse
                      ? t("workingMemoryTest.recall_example_reverse")
                      : t("workingMemoryTest.recall_example_forward")
                  }}
                </p>
              </div>
              <input
                v-model="userInput"
                :placeholder="
                  tasks[currentTask].reverse
                    ? t('workingMemoryTest.recall_placeholder_reverse')
                    : t('workingMemoryTest.recall_placeholder_forward')
                "
                class="working-memory-input text-xl text-center py-3 w-full border border-gray-300 rounded-md px-4"
                :maxlength="tasks[currentTask].spanLength"
              />
              <p class="text-sm text-slate-500 text-center">
                {{ t("workingMemoryTest.recall_span_length")
                }}{{ tasks[currentTask].spanLength
                }}{{ t("workingMemoryTest.recall_span_unit") }}
              </p>
            </div>
          </template>

          <template v-else-if="tasks[currentTask].type === 'spatial_sequence'">
            <div class="space-y-4">
              <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <h4 class="font-semibold text-blue-800 mb-2">
                  {{ t("workingMemoryTest.recall_click_instructions") }}
                </h4>
                <p class="text-sm text-blue-700">
                  {{
                    t("workingMemoryTest.recall_spatial_sequence_instructions")
                  }}
                </p>
                <p class="text-xs text-blue-600 mt-1">
                  {{ t("workingMemoryTest.recall_click_order_note") }}
                </p>
              </div>
              <div class="grid grid-cols-3 gap-4 max-w-xs mx-auto">
                <button
                  v-for="i in 9"
                  :key="i"
                  :class="[
                    'w-20 h-20 p-0 text-xl font-bold transition-all duration-200 relative rounded-md border',
                    isSpatialCellSelected(i)
                      ? 'bg-indigo-500 border-indigo-600 text-white scale-95'
                      : 'hover:bg-indigo-50 hover:border-indigo-300 border-gray-300',
                  ]"
                  @click="
                    handleSpatialClick(
                      getSpatialCellPosition(i).x,
                      getSpatialCellPosition(i).y
                    )
                  "
                  :disabled="isSpatialCellSelected(i)"
                >
                  <div
                    :class="[
                      'absolute top-1 left-1 text-xs font-mono',
                      isSpatialCellSelected(i)
                        ? 'text-indigo-200'
                        : 'text-slate-400',
                    ]"
                  >
                    {{ getSpatialCellPosition(i).x + 1 }},{{
                      getSpatialCellPosition(i).y + 1
                    }}
                  </div>
                  <span
                    v-if="isSpatialCellSelected(i)"
                    class="text-xl font-bold"
                  >
                    {{ getSpatialCellOrder(i) }}
                  </span>
                </button>
              </div>
              <p class="text-center">
                <span class="text-lg font-semibold text-indigo-600">
                  {{ t("workingMemoryTest.recall_progress")
                  }}{{ selectedCells.length }}/{{
                    tasks[currentTask].spanLength
                  }}
                </span>
              </p>
            </div>
          </template>

          <template v-else-if="tasks[currentTask].type === 'visual_matrix'">
            <div class="space-y-4">
              <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <h4 class="font-semibold text-blue-800 mb-2">
                  {{ t("workingMemoryTest.recall_select_instructions") }}
                </h4>
                <p class="text-sm text-blue-700">
                  {{ t("workingMemoryTest.recall_visual_matrix_instructions") }}
                </p>
                <p class="text-xs text-blue-600 mt-1">
                  {{ t("workingMemoryTest.recall_reclick_note") }}
                </p>
              </div>
              <div
                class="grid gap-2 max-w-md mx-auto"
                :style="{ gridTemplateColumns: `repeat(${matrixSize}, 1fr)` }"
              >
                <button
                  v-for="(cell, index) in matrixCells"
                  :key="index"
                  :class="[
                    'w-16 h-16 p-0 transition-all duration-200 relative rounded-md border',
                    isMatrixCellSelected(cell)
                      ? 'bg-indigo-500 border-indigo-600 scale-95'
                      : 'hover:bg-indigo-50 hover:border-indigo-300 border-gray-300',
                  ]"
                  @click="handleMatrixCellClick(cell.x, cell.y)"
                >
                  <div
                    :class="[
                      'absolute top-0.5 left-0.5 text-xs font-mono',
                      isMatrixCellSelected(cell)
                        ? 'text-indigo-200'
                        : 'text-slate-400',
                    ]"
                  >
                    {{ cell.x + 1 }},{{ cell.y + 1 }}
                  </div>
                </button>
              </div>
              <p class="text-center">
                <span class="text-lg font-semibold text-indigo-600">
                  {{ t("workingMemoryTest.recall_selected")
                  }}{{ selectedCells.length }}/{{
                    tasks[currentTask].spanLength
                  }}
                </span>
              </p>
            </div>
          </template>

          <button
            @click="handleAnswer"
            :disabled="
              (tasks[currentTask].type === 'digit_span' && !userInput.trim()) ||
              (tasks[currentTask].type !== 'digit_span' &&
                selectedCells.length === 0)
            "
            class="w-full bg-gradient-to-r from-indigo-600 to-blue-500 hover:from-indigo-700 hover:to-blue-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200 rounded-md"
          >
            {{ t("workingMemoryTest.submitAnswer") }}
          </button>
        </div>
      </div>
    </motion>

    <!-- Feedback Page -->
    <motion
      v-else-if="stage === 'feedback'"
      :initial="{ opacity: 0, scale: 0.9 }"
      :animate="{ opacity: 1, scale: 1 }"
      class="max-w-2xl mx-auto"
    >
      <div
        :class="[
          'rounded-lg overflow-hidden border',
          feedbackCorrect
            ? 'border-green-200 bg-green-50'
            : 'border-red-200 bg-red-50',
        ]"
      >
        <div class="p-6">
          <!-- Top Status -->
          <div class="text-center mb-6">
            <div
              :class="[
                'w-16 h-16 rounded-full mx-auto mb-4 flex items-center justify-center',
                feedbackCorrect ? 'bg-green-100' : 'bg-red-100',
              ]"
            >
              <CheckCircle
                v-if="feedbackCorrect"
                class="w-8 h-8 text-green-600"
              />
              <XCircle v-else class="w-8 h-8 text-red-600" />
            </div>
            <h3
              :class="[
                'text-xl font-semibold mb-2',
                feedbackCorrect ? 'text-green-800' : 'text-red-800',
              ]"
            >
              {{
                feedbackCorrect
                  ? t("workingMemoryTest.feedback_correct")
                  : t("workingMemoryTest.feedback_incorrect")
              }}
            </h3>
            <p
              v-if="feedbackDetails"
              :class="[
                'text-sm',
                feedbackCorrect ? 'text-green-600' : 'text-red-600',
              ]"
            >
              {{ t("workingMemoryTest.feedback_accuracy")
              }}{{ feedbackDetails.accuracy }}%
            </p>
          </div>

          <!-- Answer Comparison -->
          <div v-if="feedbackDetails && !feedbackCorrect" class="space-y-4">
            <div class="bg-white rounded-lg p-4 border">
              <h4 class="font-semibold text-slate-800 mb-3">
                {{ t("workingMemoryTest.feedback_comparison") }}
              </h4>

              <div class="grid gap-3">
                <div class="flex flex-col sm:flex-row gap-2">
                  <span class="font-medium text-green-700 min-w-[80px]">{{
                    t("workingMemoryTest.feedback_correct_answer")
                  }}</span>
                  <span
                    class="font-mono text-green-800 bg-green-50 px-2 py-1 rounded"
                  >
                    {{
                      formatAnswer(
                        feedbackDetails.correctAnswer,
                        feedbackDetails.taskType
                      )
                    }}
                  </span>
                </div>

                <div class="flex flex-col sm:flex-row gap-2">
                  <span class="font-medium text-red-700 min-w-[80px]">{{
                    t("workingMemoryTest.feedback_your_answer")
                  }}</span>
                  <span
                    class="font-mono text-red-800 bg-red-50 px-2 py-1 rounded"
                  >
                    {{
                      feedbackDetails.userAnswer.length > 0
                        ? formatAnswer(
                            feedbackDetails.userAnswer,
                            feedbackDetails.taskType
                          )
                        : t("workingMemoryTest.feedback_not_answered")
                    }}
                  </span>
                </div>
              </div>
            </div>

            <!-- Error Analysis -->
            <div
              v-if="feedbackDetails.errors.length > 0"
              class="bg-orange-50 border border-orange-200 rounded-lg p-4"
            >
              <h4
                class="font-semibold text-orange-800 mb-3 flex items-center gap-2"
              >
                <XCircle class="w-4 h-4" />
                {{ t("workingMemoryTest.feedback_error_analysis") }}
              </h4>
              <ul class="space-y-2">
                <li
                  v-for="(error, index) in feedbackDetails.errors"
                  :key="index"
                  class="text-sm text-orange-700 flex items-start gap-2"
                >
                  <span
                    class="w-1.5 h-1.5 bg-orange-400 rounded-full mt-2 flex-shrink-0"
                  ></span>
                  <span>{{ error }}</span>
                </li>
              </ul>
            </div>

            <!-- Hint -->
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
              <h4 class="font-semibold text-blue-800 mb-2">
                {{ t("workingMemoryTest.feedback_hint") }}
              </h4>
              <p class="text-sm text-blue-700">
                {{
                  getHintText(
                    tasks[currentTask].type,
                    tasks[currentTask].reverse
                  )
                }}
              </p>
            </div>
          </div>

          <!-- Correct Feedback -->
          <div v-if="feedbackCorrect" class="text-center">
            <p class="text-green-700 mb-4">
              {{ t("workingMemoryTest.feedback_correct_praise") }}
            </p>
            <div class="bg-green-100 border border-green-200 rounded-lg p-3">
              <p class="text-sm text-green-700">
                {{ t("workingMemoryTest.feedback_correct_excellent") }}
              </p>
            </div>
          </div>

          <!-- Continue Button -->
          <div class="mt-6 text-center">
            <button
              @click="handleContinue"
              class="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white px-8 py-2 shadow-lg hover:shadow-xl transition-all duration-200 rounded-md"
            >
              {{
                currentTask < tasks.length - 1
                  ? t("workingMemoryTest.continue_next")
                  : t("workingMemoryTest.view_results")
              }}
            </button>
          </div>
        </div>
      </div>
    </motion>

    <!-- Results Page -->
    <motion
      v-else-if="stage === 'results'"
      :initial="{ opacity: 0, y: 20 }"
      :animate="{ opacity: 1, y: 0 }"
      class="max-w-4xl mx-auto space-y-6"
    >
      <div
        class="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg rounded-lg overflow-hidden"
      >
        <div class="text-center px-6 pt-6">
          <div
            class="w-16 h-16 bg-gradient-to-br from-indigo-600 to-blue-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
          >
            <Brain class="w-8 h-8 text-white" />
          </div>
          <h2 class="text-2xl text-slate-800 font-bold">
            {{ t("workingMemoryTest.results_title") }}
          </h2>
        </div>

        <div class="space-y-6 px-6 pb-6">
          <div class="text-center space-y-4">
            <div class="text-6xl font-bold text-indigo-600">
              {{ Math.round((score / tasks.length) * 100) }}
            </div>
            <div :class="['text-xl font-semibold', getRating().color]">
              {{ getRating().text }}
            </div>
          </div>

          <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div class="text-center p-4 bg-green-50 rounded-lg">
              <div class="text-2xl font-bold text-green-600">{{ score }}</div>
              <div class="text-sm text-gray-600">
                {{ t("workingMemoryTest.results_correct_tasks") }}
              </div>
            </div>
            <div class="text-center p-4 bg-blue-50 rounded-lg">
              <div class="text-2xl font-bold text-blue-600">
                {{ tasks.length }}
              </div>
              <div class="text-sm text-gray-600">
                {{ t("workingMemoryTest.results_total_tasks") }}
              </div>
            </div>
            <div class="text-center p-4 bg-purple-50 rounded-lg">
              <div class="text-2xl font-bold text-purple-600">
                {{
                  (
                    responses.reduce((sum, r) => sum + r.spanLength, 0) /
                    responses.length
                  ).toFixed(1)
                }}
              </div>
              <div class="text-sm text-gray-600">
                {{ t("workingMemoryTest.results_average_span") }}
              </div>
            </div>
            <div class="text-center p-4 bg-orange-50 rounded-lg">
              <div class="text-2xl font-bold text-orange-600">
                {{ Math.round((Date.now() - startTime) / 1000) }}s
              </div>
              <div class="text-sm text-gray-600">
                {{ t("workingMemoryTest.results_total_time") }}
              </div>
            </div>
          </div>

          <!-- Task Type Analysis -->
          <div class="space-y-3">
            <h3 class="text-lg font-semibold text-slate-800">
              {{ t("workingMemoryTest.results_breakdown") }}
            </h3>
            <div
              v-for="([type, stats], index) in Object.entries(getTypeStats())"
              :key="index"
              class="bg-slate-50 rounded-lg p-4"
            >
              <div class="flex justify-between items-center mb-2">
                <span class="font-medium text-slate-700">
                  {{
                    type === "digit_span"
                      ? t("workingMemoryTest.results_digit_span")
                      : type === "spatial_sequence"
                      ? t("workingMemoryTest.results_spatial_sequence")
                      : type === "visual_matrix"
                      ? t("workingMemoryTest.results_visual_matrix")
                      : type
                  }}
                </span>
                <span
                  :class="[
                    'px-2 py-1 rounded text-xs font-medium',
                    stats.accuracy >= 80
                      ? 'bg-green-100 text-green-800'
                      : 'bg-gray-100 text-gray-800',
                  ]"
                >
                  {{ stats.accuracy }}%
                </span>
              </div>
              <div class="text-sm text-slate-600">
                {{ t("workingMemoryTest.results_avg_span_label") }}
                {{ stats.avgSpan }} |
                {{ t("workingMemoryTest.results_completed_tasks_label") }}
                {{ stats.count }}
              </div>
            </div>
          </div>

          <div class="flex gap-4">
            <button
              @click="resetTest"
              class="flex-1 border-2 border-slate-300 hover:border-green-500 hover:bg-green-50 hover:text-green-700 transition-all duration-200 rounded-md py-2 flex items-center justify-center"
            >
              <RotateCcw class="w-4 h-4 mr-2" />
              {{ t("workingMemoryTest.retest") }}
            </button>
            <button
              @click="handleComplete"
              class="flex-1 bg-gradient-to-r from-green-500 to-emerald-500 text-white hover:from-green-600 hover:to-emerald-600 shadow-md hover:shadow-lg transition-all duration-200 rounded-md py-2"
            >
              {{ t("workingMemoryTest.saveResult") }}
            </button>
          </div>
        </div>
      </div>
    </motion>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import {
  Brain,
  Clock,
  Trophy,
  Star,
  Target,
  ArrowRight,
  RotateCcw,
  CheckCircle,
  XCircle,
} from "lucide-vue-next";

const { t } = useI18n();
// Define properties
const props = defineProps({
  onComplete: {
    type: Function,
    required: true,
  },
});

// State definition
const stage = ref("instructions");
const currentTask = ref(0);
const tasks = ref([]);
const currentSequence = ref([]);
const currentIndex = ref(0);
const userInput = ref("");
const selectedCells = ref([]);
const responses = ref([]);
const startTime = ref(0);
const taskStartTime = ref(0);
const score = ref(0);
const showFeedback = ref(false);
const feedbackCorrect = ref(false);
const feedbackDetails = ref(null);
const matrixCells = ref([]);
const matrixSize = ref(4);
const presentingItem = ref(null);

const TOTAL_TASKS = 12;
const DIGITS = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// Generate test tasks
const generateTasks = () => {
  const tasks = [];
  let taskId = 1;

  // Digit Span Test (forward and reverse)
  for (let length = 3; length <= 7; length++) {
    tasks.push({
      id: taskId++,
      type: "digit_span",
      instruction: `Remember this ${length}-digit sequence, then enter it in order`,
      spanLength: length,
      reverse: false,
      difficulty: length <= 4 ? "easy" : length <= 6 ? "medium" : "hard",
    });

    if (length >= 4) {
      tasks.push({
        id: taskId++,
        type: "digit_span",
        instruction: `Remember this ${length}-digit sequence, then enter it in reverse order`,
        spanLength: length,
        reverse: true,
        difficulty: length <= 4 ? "easy" : length <= 6 ? "medium" : "hard",
      });
    }
  }

  // Spatial Sequence Test
  for (let length = 3; length <= 6; length++) {
    tasks.push({
      id: taskId++,
      type: "spatial_sequence",
      instruction: `Remember the order in which the squares light up, then click them in the same order`,
      spanLength: length,
      difficulty: length <= 4 ? "easy" : length <= 5 ? "medium" : "hard",
    });
  }

  // Visual Matrix Test
  for (let count = 3; count <= 8; count += 2) {
    tasks.push({
      id: taskId++,
      type: "visual_matrix",
      instruction: `Remember the positions of the highlighted squares, then click those positions`,
      spanLength: count,
      difficulty: count <= 4 ? "easy" : count <= 6 ? "medium" : "hard",
    });
  }

  // Randomly select and sort tasks
  return tasks.sort(() => Math.random() - 0.5).slice(0, TOTAL_TASKS);
};

// Generate digit sequence
const generateDigitSequence = (length) => {
  const sequence = [];
  for (let i = 0; i < length; i++) {
    sequence.push(DIGITS[Math.floor(Math.random() * DIGITS.length)]);
  }
  return sequence;
};

// Generate spatial sequence
const generateSpatialSequence = (length) => {
  const sequence = [];
  const used = new Set();

  for (let i = 0; i < length; i++) {
    let x, y, key;
    do {
      x = Math.floor(Math.random() * 3);
      y = Math.floor(Math.random() * 3);
      key = `${x},${y}`;
    } while (used.has(key));

    used.add(key);
    sequence.push({ x, y });
  }

  return sequence;
};

// Generate visual matrix
const generateVisualMatrix = (count) => {
  const cells = [];
  const highlighted = [];

  // Create all cells
  for (let x = 0; x < matrixSize.value; x++) {
    for (let y = 0; y < matrixSize.value; y++) {
      cells.push({ x, y, highlighted: false });
    }
  }

  // Randomly select cells to highlight
  const shuffled = [...cells].sort(() => Math.random() - 0.5);
  for (let i = 0; i < count; i++) {
    shuffled[i].highlighted = true;
    highlighted.push({ x: shuffled[i].x, y: shuffled[i].y });
  }

  matrixCells.value = cells;
  return highlighted;
};

// Start presenting sequence
const startPresenting = async () => {
  const task = tasks.value[currentTask.value];

  // Preparation phase - 3 second countdown
  stage.value = "presenting";

  // Countdown
  for (let countdown = 3; countdown > 0; countdown--) {
    presentingItem.value = `Ready... ${countdown}`;
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }

  presentingItem.value = "Start!";
  await new Promise((resolve) => setTimeout(resolve, 500));

  currentIndex.value = 0;

  if (task.type === "digit_span") {
    const sequence = generateDigitSequence(task.spanLength);
    currentSequence.value = sequence;

    // Present digits one by one
    for (let i = 0; i < sequence.length; i++) {
      presentingItem.value = sequence[i];
      currentIndex.value = i;
      await new Promise((resolve) => setTimeout(resolve, 1200));
    }
  } else if (task.type === "spatial_sequence") {
    const sequence = generateSpatialSequence(task.spanLength);
    currentSequence.value = sequence;

    presentingItem.value = t("workingMemoryTest.presenting_watch_highlight");
    await new Promise((resolve) => setTimeout(resolve, 800));

    // Highlight spatial positions one by one
    for (let i = 0; i < sequence.length; i++) {
      presentingItem.value = sequence[i];
      currentIndex.value = i;
      await new Promise((resolve) => setTimeout(resolve, 1000));
      presentingItem.value = null;
      await new Promise((resolve) => setTimeout(resolve, 300));
    }
  } else if (task.type === "visual_matrix") {
    const highlighted = generateVisualMatrix(task.spanLength);
    currentSequence.value = highlighted;

    presentingItem.value = t("workingMemoryTest.presenting_watch_positions");
    await new Promise((resolve) => setTimeout(resolve, 500));

    // Display matrix for 2.5 seconds
    await new Promise((resolve) => setTimeout(resolve, 2500));
    matrixCells.value = matrixCells.value.map((cell) => ({
      ...cell,
      highlighted: false,
    }));
  }

  presentingItem.value = null;
  stage.value = "recall";
};

// Analyze error details
const analyzeErrors = (userSeq, correctSeq, taskType) => {
  const errors = [];

  if (taskType === "digit_span") {
    const task = tasks.value[currentTask.value];
    if (userSeq.length !== correctSeq.length) {
      errors.push(
        `Length error: you should have entered ${correctSeq.length} digits, but you entered ${userSeq.length}`
      );
    }

    const minLength = Math.min(userSeq.length, correctSeq.length);
    for (let i = 0; i < minLength; i++) {
      if (userSeq[i] !== correctSeq[i]) {
        errors.push(
          `Error at position ${i + 1}: should be ${correctSeq[i]}, but you entered ${userSeq[i]}`
        );
      }
    }

    if (userSeq.length > correctSeq.length) {
      errors.push(`You entered ${userSeq.length - correctSeq.length} extra digits`);
    } else if (userSeq.length < correctSeq.length) {
      errors.push(`You missed ${correctSeq.length - userSeq.length} digits`);
    }
  } else if (taskType === "spatial_sequence") {
    if (userSeq.length !== correctSeq.length) {
      errors.push(
        `Incorrect number of clicks: you should have clicked ${correctSeq.length} squares, but you clicked ${userSeq.length}`
      );
    }

    const minLength = Math.min(userSeq.length, correctSeq.length);
    for (let i = 0; i < minLength; i++) {
      const userPos = userSeq[i];
      const correctPos = correctSeq[i];
      if (
        !userPos ||
        !correctPos ||
        userPos.x !== correctPos.x ||
        userPos.y !== correctPos.y
      ) {
        const userPosStr = userPos
          ? `(${userPos.x + 1}, ${userPos.y + 1})`
          : "Not selected";
        const correctPosStr = `(${correctPos.x + 1}, ${correctPos.y + 1})`;
        errors.push(
          `Error at step ${i + 1}: you should have clicked position ${correctPosStr}, but you clicked ${userPosStr}`
        );
      }
    }
  } else if (taskType === "visual_matrix") {
    const correctPositions = correctSeq.map((pos) => `${pos.x},${pos.y}`);
    const selectedPositions = userSeq.map((pos) => `${pos.x},${pos.y}`);

    const missed = correctPositions.filter(
      (pos) => !selectedPositions.includes(pos)
    );
    const wrongSelected = selectedPositions.filter(
      (pos) => !correctPositions.includes(pos)
    );

    if (missed.length > 0) {
      const missedCoords = missed.map((pos) => {
        const [x, y] = pos.split(",").map(Number);
        return `(${x + 1}, ${y + 1})`;
      });
      errors.push(`Missed positions: ${missedCoords.join(", ")}`);
    }

    if (wrongSelected.length > 0) {
      const wrongCoords = wrongSelected.map((pos) => {
        const [x, y] = pos.split(",").map(Number);
        return `(${x + 1}, ${y + 1})`;
      });
      errors.push(`Incorrect selections: ${wrongCoords.join(", ")}`);
    }
  }

  return errors;
};

// Handle user answer
const handleAnswer = () => {
  const task = tasks.value[currentTask.value];
  const reactionTime = Date.now() - taskStartTime.value;
  let accuracy = 0;
  let userSequence = [];
  let correctSequence = [];

  if (task.type === "digit_span") {
    userSequence = userInput.value
      .split("")
      .map((d) => parseInt(d))
      .filter((n) => !isNaN(n));
    correctSequence = task.reverse
      ? [...currentSequence.value].reverse()
      : [...currentSequence.value];
    accuracy = calculateSequenceAccuracy(userSequence, correctSequence);
  } else if (task.type === "spatial_sequence") {
    userSequence = selectedCells.value || [];
    correctSequence = currentSequence.value || [];
    accuracy = calculateSpatialAccuracy(userSequence, correctSequence);
  } else if (task.type === "visual_matrix") {
    userSequence = selectedCells.value || [];
    correctSequence = currentSequence.value || [];
    accuracy = calculateMatrixAccuracy(userSequence, correctSequence);
  }

  const response = {
    sequence: userSequence,
    accuracy,
    reactionTime,
    spanLength: task.spanLength,
    taskType: task.type,
  };

  responses.value = [...responses.value, response];

  const isCorrect = accuracy >= 0.8;
  if (isCorrect) {
    score.value = score.value + 1;
  }

  // Analyze errors
  const errors = isCorrect
    ? []
    : analyzeErrors(userSequence, correctSequence, task.type);

  // Show feedback
  feedbackCorrect.value = isCorrect;
  feedbackDetails.value = {
    correctAnswer: correctSequence,
    userAnswer: userSequence,
    accuracy: Math.round(accuracy * 100),
    taskType: task.type,
    errors,
  };
  showFeedback.value = true;
  stage.value = "feedback";
};

// Continue to next question
const handleContinue = () => {
  showFeedback.value = false;
  feedbackDetails.value = null;
  userInput.value = "";
  selectedCells.value = [];

  if (currentTask.value < tasks.value.length - 1) {
    currentTask.value = currentTask.value + 1;
    stage.value = "test";
  } else {
    stage.value = "results";
  }
};

// Calculate sequence accuracy
const calculateSequenceAccuracy = (userSeq, correctSeq) => {
  if (userSeq.length === 0) return 0;

  const minLength = Math.min(userSeq.length, correctSeq.length);
  let correct = 0;

  for (let i = 0; i < minLength; i++) {
    if (userSeq[i] === correctSeq[i]) {
      correct++;
    }
  }

  return correct / correctSeq.length;
};

// Calculate spatial sequence accuracy
const calculateSpatialAccuracy = (userSeq, correctSeq) => {
  if (
    !userSeq ||
    userSeq.length === 0 ||
    !correctSeq ||
    correctSeq.length === 0
  )
    return 0;

  const minLength = Math.min(userSeq.length, correctSeq.length);
  let correct = 0;

  for (let i = 0; i < minLength; i++) {
    const userItem = userSeq[i];
    const correctItem = correctSeq[i];
    if (
      userItem &&
      correctItem &&
      typeof userItem.x === "number" &&
      typeof userItem.y === "number" &&
      typeof correctItem.x === "number" &&
      typeof correctItem.y === "number" &&
      userItem.x === correctItem.x &&
      userItem.y === correctItem.y
    ) {
      correct++;
    }
  }

  return correct / correctSeq.length;
};

// Calculate matrix accuracy
const calculateMatrixAccuracy = (selected, correct) => {
  if (!selected || !correct || selected.length === 0 || correct.length === 0)
    return 0;

  const correctPositions = correct
    .filter(
      (pos) => pos && typeof pos.x === "number" && typeof pos.y === "number"
    )
    .map((pos) => `${pos.x},${pos.y}`);
  const selectedPositions = selected
    .filter(
      (pos) => pos && typeof pos.x === "number" && typeof pos.y === "number"
    )
    .map((pos) => `${pos.x},${pos.y}`);

  const truePositives = selectedPositions.filter((pos) =>
    correctPositions.includes(pos)
  ).length;
  const falsePositives = selectedPositions.filter(
    (pos) => !correctPositions.includes(pos)
  ).length;
  const falseNegatives = correctPositions.filter(
    (pos) => !selectedPositions.includes(pos)
  ).length;

  if (truePositives + falsePositives + falseNegatives === 0) return 1;

  return truePositives / (truePositives + falsePositives + falseNegatives);
};

// Handle spatial sequence click
const handleSpatialClick = (x, y) => {
  if (typeof x === "number" && typeof y === "number") {
    selectedCells.value = [...selectedCells.value, { x, y }];
  }
};

// Handle matrix cell click
const handleMatrixCellClick = (x, y) => {
  if (typeof x !== "number" || typeof y !== "number") return;

  selectedCells.value = selectedCells.value.filter(
    (cell) => !(cell && cell.x === x && cell.y === y)
  );

  const existing = selectedCells.value.find(
    (cell) => cell && cell.x === x && cell.y === y
  );
  if (!existing) {
    selectedCells.value = [...selectedCells.value, { x, y }];
  }
};

// Start test
const handleStartTest = () => {
  const generatedTasks = generateTasks();
  tasks.value = generatedTasks;
  stage.value = "test";
  startTime.value = Date.now();
};

// Complete test
const handleComplete = () => {
  const totalTasks = tasks.value.length;
  const correctAnswers = score.value;
  const accuracy = Math.round((correctAnswers / totalTasks) * 100);
  const timeUsed = Math.round((Date.now() - startTime.value) / 1000);
  const averageSpan =
    responses.value.reduce((sum, r) => sum + r.spanLength, 0) /
    responses.value.length;
  const averageReactionTime =
    responses.value.reduce((sum, r) => sum + r.reactionTime, 0) /
    responses.value.length;

  // Statistics by task type
  const typeStats = {};

  responses.value.forEach((response) => {
    const type = response.taskType;
    if (!typeStats[type]) {
      typeStats[type] = { accuracy: 0, count: 0, avgSpan: 0 };
    }
    typeStats[type].accuracy += response.accuracy;
    typeStats[type].avgSpan += response.spanLength;
    typeStats[type].count++;
  });

  // Calculate average
  Object.keys(typeStats).forEach((type) => {
    const stats = typeStats[type];
    stats.accuracy = Math.round((stats.accuracy / stats.count) * 100);
    stats.avgSpan = Math.round((stats.avgSpan / stats.count) * 10) / 10;
  });

  const result = {
    id: Date.now().toString(),
    testType: "working-memory",
    score: accuracy,
    completedAt: new Date(),
    duration: timeUsed,
    details: {
      totalTasks,
      correctAnswers,
      accuracy,
      averageSpanLength: Math.round(averageSpan * 10) / 10,
      maxSpanLength: Math.max(...responses.value.map((r) => r.spanLength)),
      averageReactionTime: Math.round(averageReactionTime),
      typeBreakdown: Object.entries(typeStats).map(([type, stats]) => ({
        type:
          type === "digit_span"
            ? t("workingMemoryTest.results_digit_span")
            : type === "spatial_sequence"
            ? t("workingMemoryTest.results_spatial_sequence")
            : type === "visual_matrix"
            ? t("workingMemoryTest.results_visual_matrix")
            : type,
        accuracy: stats.accuracy,
        avgSpan: stats.avgSpan,
        count: stats.count,
      })),
      totalQuestions: totalTasks,
      correctQuestions: correctAnswers,
      averageTime: timeUsed,
      difficulty: t("workingMemoryTest.adaptive"),
    },
  };

  props.onComplete(result);
};

// Format answer display
const formatAnswer = (answer, taskType) => {
  if (taskType === "digit_span") {
    return answer.join("");
  } else if (taskType === "spatial_sequence") {
    return answer
      .map((pos, i) => `${i + 1}:(${pos.x + 1},${pos.y + 1})`)
      .join(" → ");
  } else if (taskType === "visual_matrix") {
    return answer.map((pos) => `(${pos.x + 1},${pos.y + 1})`).join(", ");
  }
  return "";
};

// Get hint text
const getHintText = (taskType, isReverse) => {
  if (taskType === "digit_span" && isReverse) {
    return t("workingMemoryTest.hint_digit_span_reverse");
  } else if (taskType === "digit_span") {
    return t("workingMemoryTest.hint_digit_span_forward");
  } else if (taskType === "spatial_sequence") {
    return t("workingMemoryTest.hint_spatial_sequence");
  } else if (taskType === "visual_matrix") {
    return t("workingMemoryTest.hint_visual_matrix");
  }
  return t("workingMemoryTest.hint_general");
};

// Get type statistics
const getTypeStats = () => {
  const typeStats = {};

  responses.value.forEach((response) => {
    const type = response.taskType;
    if (!typeStats[type]) {
      typeStats[type] = { accuracy: 0, count: 0, avgSpan: 0 };
    }
    typeStats[type].accuracy += response.accuracy;
    typeStats[type].avgSpan += response.spanLength;
    typeStats[type].count++;
  });

  // Calculate average
  Object.keys(typeStats).forEach((type) => {
    const stats = typeStats[type];
    stats.accuracy = Math.round((stats.accuracy / stats.count) * 100);
    stats.avgSpan = Math.round((stats.avgSpan / stats.count) * 10) / 10;
  });

  return typeStats;
};

// Get rating
const getRating = () => {
  const accuracy = Math.round((score.value / tasks.value.length) * 100);
  if (accuracy >= 90)
    return {
      text: t("workingMemoryTest.rating_expert"),
      color: "text-yellow-500",
    };
  if (accuracy >= 80)
    return {
      text: t("workingMemoryTest.rating_excellent"),
      color: "text-green-500",
    };
  if (accuracy >= 70)
    return { text: t("workingMemoryTest.rating_good"), color: "text-blue-500" };
  if (accuracy >= 60)
    return {
      text: t("workingMemoryTest.rating_average"),
      color: "text-gray-500",
    };
  return {
    text: t("workingMemoryTest.rating_needs_improvement"),
    color: "text-orange-500",
  };
};

// Reset test
const resetTest = () => {
  stage.value = "instructions";
  currentTask.value = 0;
  tasks.value = [];
  currentSequence.value = [];
  currentIndex.value = 0;
  userInput.value = "";
  selectedCells.value = [];
  responses.value = [];
  startTime.value = 0;
  taskStartTime.value = 0;
  score.value = 0;
  showFeedback.value = false;
  feedbackCorrect.value = false;
  feedbackDetails.value = null;
  matrixCells.value = [];
  presentingItem.value = null;
};

// Is spatial sequence cell highlighted
const isSpatialCellHighlighted = (index) => {
  if (!presentingItem.value || typeof presentingItem.value !== "object")
    return false;

  const position = getSpatialCellPosition(index);
  return (
    presentingItem.value.x === position.x &&
    presentingItem.value.y === position.y
  );
};

// Get spatial sequence cell position
const getSpatialCellPosition = (index) => {
  const i = index - 1;
  return {
    x: i % 3,
    y: Math.floor(i / 3),
  };
};

// Is spatial sequence cell selected
const isSpatialCellSelected = (index) => {
  const position = getSpatialCellPosition(index);
  return selectedCells.value.some(
    (cell) => cell.x === position.x && cell.y === position.y
  );
};

// Get spatial sequence cell order
const getSpatialCellOrder = (index) => {
  const position = getSpatialCellPosition(index);
  const indexInSelected = selectedCells.value.findIndex(
    (cell) => cell.x === position.x && cell.y === position.y
  );
  return indexInSelected >= 0 ? indexInSelected + 1 : 0;
};

// Is matrix cell selected
const isMatrixCellSelected = (cell) => {
  return selectedCells.value.some(
    (selected) => selected.x === cell.x && selected.y === cell.y
  );
};

// Start current task
onMounted(() => {
  if (stage.value === "test" && tasks.value.length > 0) {
    taskStartTime.value = Date.now();
  }
});
</script>

<style scoped>
.working-memory-input {
  letter-spacing: 0.5em;
  font-family: monospace;
}
</style>
